# coding: utf8
'''验证码 处理 通用方法'''

from worktasks.settings import BASE_DIR

import cStringIO
from PIL import Image, ImageDraw, ImageFont, ImageFilter
import random, string, os

# 字体的位置
font_path = os.path.join(BASE_DIR, 'static/fonts/arial.ttf')
# 生成几位数的验证码
number = 4
# 生成验证码图片的高度和宽度
size = (100, 30)
# 背景颜色，默认为白色
bgcolor = (238, 238, 238)
# 字体颜色，默认为蓝色
fontcolor = (0, 0, 255)
# 干扰线颜色。默认为红色
linecolor = (255, 0, 0)
# 是否要加入干扰线
drawline = True
# 加入干扰线条数
linenumber = 0
# 干扰点出现的概率，大小范围[0, 100]
pointchance = 2


def random_text():
	'''随机出数字字母'''
	source = list(string.ascii_letters)
	for index in range(0, 10):
		source.append(str(index))
	return ''.join(random.sample(source, number))  # number是生成验证码的位数


def draw_line(draw, width, height):
	'''绘制干扰线'''
	begin = (random.randint(0, width), random.randint(0, height))
	end = (random.randint(0, width), random.randint(0, height))
	draw.line([begin, end], fill=linecolor)

def create_points(draw, width, height):
	'''绘制干扰点'''
	chance = min(100, max(0, int(pointchance)))  # 大小限制在[0, 100]

	for w in range(width):
		for h in range(height):
			tmp = random.randint(0, 100)
			if tmp > 100 - chance:
				draw.point((w, h), fill=(0, 0, 0))


def get_captcha():
	width, height = size  # 宽和高
	image = Image.new('RGBA', (width, height), bgcolor)  # 创建图片
	font = ImageFont.truetype(font_path, 25)  # 验证码的字体和字体大小
	draw = ImageDraw.Draw(image)  # 创建画笔
	text = random_text()  # 生成字符串

	font_width, font_height = font.getsize(text)
	draw.text(((width - font_width) / number, (height - font_height) / number), text, \
			  font=font, fill=fontcolor)  # 填充字符串

	if drawline:
		# 绘制干扰线
		for i in range(linenumber):
			draw_line(draw, width, height)

	image = image.transform((width + 20, height + 10),\
							Image.AFFINE,\
							(1, -0.3, 0, -0.1, 1, 0),\
							Image.BILINEAR)  # 创建扭曲
	image = image.filter(ImageFilter.EDGE_ENHANCE_MORE)  # 滤镜，边界加强

	del draw	# 清除画笔
	buf = cStringIO.StringIO()  # 创建内存缓存区, 用于存储图片
	image.save(buf, 'png')
	# return the image data stream as image/jpeg format,
	# browser will treat it as an image
	# return HttpResponse(buf.getvalue(), 'image/png')
	return (buf.getvalue(), text)

class CaptchaSession:
	'''验证码session类'''
	def get_captcha_session_key(self, url_path, csrf_token):
		'''拼接验证码session的键'''
		return '_'.join(['Captcha', url_path, csrf_token])